#include "../common_defs.h"
#include "../vm/c_vm.h"
#include "../lexer/c_lexer.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <stdint.h>


// 定义全局变量
int token = 0;
int token_val = 0;
char *src = NULL, *old_src = NULL;
int line = 1;
int column = 1;
intptr_t *current_id = NULL;
intptr_t *symbols = NULL;
intptr_t *idmain = NULL;
char token_buffer[2048] = {0};  // 词法分析器的token缓冲区

// 虚拟机相关全局变量
int poolsize = 0;
intptr_t *text = NULL;
char *data = NULL;
char *data_start = NULL;
intptr_t *stack = NULL;
intptr_t *pc = NULL, *bp = NULL, *sp = NULL;
intptr_t *text_start = NULL, *stack_start = NULL, *symbols_start = NULL;
intptr_t ax = 0, cycle = 0;
ScopeStack* scope_stack;

// 解析器相关
int basetype = 0;
int expr_type = 0;
int index_of_bp = 0;
// 获取符号类名称
const char* get_symbol_class_name(SymClass class) {
    switch(class) {
        case SYM_GLOBAL: return "SYM_GLOBAL";
        case SYM_LOCAL: return "SYM_LOCAL";
        case SYM_FUNCTION: return "SYM_FUNCTION";
        case SYM_PARAM: return "SYM_PARAM";
        case SYM_SYSTEM: return "SYM_SYSTEM";
        case SYM_ENUM: return "SYM_ENUM";
        case SYM_BLOCK: return "SYM_BLOCK";
        default: return "UNKNOWN";
    }
}

// 获取数据类型名称
const char* get_data_type_name(DataType type) {
    switch(type) {
        case TYPE_INT: return "TYPE_INT";
        case TYPE_CHAR: return "TYPE_CHAR";
        case TYPE_VOID: return "TYPE_VOID";
        case TYPE_PTR_INT: return "TYPE_PTR_INT";
        case TYPE_PTR_CHAR: return "TYPE_PTR_CHAR";
        default: return "UNKNOWN";
    }
}

// 打印作用域头部信息
void print_scope_header(Scope* scope) {
    if (!scope) {
        printf("=== NULL Scope ===\n");
        return;
    }
    
    printf("\n=== Scope Level: %d ===\n", scope->level);
    
    if (scope->parent) {
        printf("Parent: Level %d\n", scope->parent->level);
    } else {
        printf("Parent: NULL\n");
    }
    
    // 统计符号数量
    int symbol_count = 0;
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* sym = scope->hash_table[i];
        while (sym) {
            symbol_count++;
            sym = sym->next;
        }
    }
    printf("Symbol Count: %d\n", symbol_count);
}

// 打印函数参数信息
void print_function_params(Param* params) {
    if (!params) {
        printf("    Parameters: None\n");
        return;
    }
    
    printf("    Parameters:\n");
    int index = 0;
    Param* current = params;
    while (current) {
        printf("      [%d] %s %s (offset: %lld)\n", 
               index, 
               get_data_type_name(current->type),
               current->name ? current->name : "unnamed",
               (long long)current->offset);
        current = current->next;
        index++;
    }
}

// 打印初始化信息
void print_initialization_info(SymInfo* info) {
    if (!info->is_init) {
        printf("    Initialized: No\n");
        return;
    }
    
    printf("    Initialized: Yes\n");
    if (info->is_pointer > 0) {
        printf("    Init Value: 0x%llx (pointer)\n", (unsigned long long)info->dvalue.ptr_val);
    } else {
        printf("    Init Value: %lld\n", (long long)info->dvalue.int_val);
    }
}

// 打印符号详细信息
void print_symbol_details(SymInfo* info) {
    if (!info) {
        printf("    Info: NULL\n");
        return;
    }
    
    printf("  - Class: %s\n", get_symbol_class_name(info->sym_class));
    printf("  - Type: %s\n", get_data_type_name(info->data_type));
    printf("  - Address: 0x%llx\n", (unsigned long long)info->addr);
    printf("  - Pointer Level: %lld\n", (long long)info->is_pointer);
    
    print_initialization_info(info);
    
    // 如果是函数，打印参数信息
    if (info->sym_class == SYM_FUNCTION) {
        print_function_params(info->params);
        if (info->func_scope) {
            printf("  - Function Scope: Level %d\n", info->func_scope->level);
        }
    }
    
    // 如果是代码块，打印作用域信息
    if (info->sym_class == SYM_BLOCK) {
        if (info->func_scope) {
            printf("  - Block Scope: Level %d\n", info->func_scope->level);
        }
    }
}

// 打印符号信息
void print_symbol_info(Symbol* symbol) {
    if (!symbol) {
        printf("Symbol: NULL\n");
        return;
    }
    
    printf("\nSymbol: %s\n", symbol->name ? symbol->name : "unnamed");
    print_symbol_details(symbol->info);
}

// 内部遍历函数（不带开始/结束标记）
static void traverse_symbol_table_internal(Scope* scope) {
    if (!scope) {
        printf("Error: NULL scope in internal traversal\n");
        return;
    }
    
    // 打印作用域头部信息
    //print_scope_header(scope);
    
    // 遍历当前作用域的哈希表
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* symbol = scope->hash_table[i];
        while (symbol) {
            print_symbol_info(symbol);
            
            // 如果是函数或代码块且有作用域，递归遍历
            if (symbol->info && 
                (symbol->info->sym_class == SYM_FUNCTION || symbol->info->sym_class == SYM_BLOCK) && 
                symbol->info->func_scope) {
                traverse_symbol_table_internal(symbol->info->func_scope);
            }
            
            symbol = symbol->next;
        }
    }
}

// 公共接口函数（带开始/结束标记）
void traverse_symbol_table(Scope* scope) {
    // 如果传入NULL，从全局作用域开始
    if (!scope) {
        if (!scope_stack || scope_stack->top <= 0) {
            printf("Error: No global scope available\n");
            return;
        }
        scope = scope_stack->stack[0]; // 全局作用域
    }
    
    // 打印开始标记
    printf("=== Symbol Table Traversal ===\n");
    
    // 调用内部递归函数
    traverse_symbol_table_internal(scope);
    
    // 打印结束标记
    printf("\n=== Traversal Complete ===\n");
}

// 格式化符号表到字符串的辅助函数
static void format_scope_header_to_buffer(Scope* scope, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!scope) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "=== NULL Scope ===\n");
        *current_pos += len;
        return;
    }
    
    int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, 
                      "\n=== Scope Level: %d ===\n", scope->level);
    *current_pos += len;
    
    if (scope->parent) {
        len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, 
                      "Parent: Level %d\n", scope->parent->level);
    } else {
        len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "Parent: NULL\n");
    }
    *current_pos += len;
    
    // 统计符号数量
    int symbol_count = 0;
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* sym = scope->hash_table[i];
        while (sym) {
            symbol_count++;
            sym = sym->next;
        }
    }
    len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, 
                  "Symbol Count: %d\n", symbol_count);
    *current_pos += len;
}

static void format_function_params_to_buffer(Param* params, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!params) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "    Parameters: None\n");
        *current_pos += len;
        return;
    }
    
    int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "    Parameters:\n");
    *current_pos += len;
    
    int index = 0;
    Param* current = params;
    while (current) {
        len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                      "      [%d] %s %s (offset: %lld)\n", 
                      index, 
                      get_data_type_name(current->type),
                      current->name ? current->name : "unnamed",
                      (long long)current->offset);
        *current_pos += len;
        current = current->next;
        index++;
    }
}

static void format_initialization_info_to_buffer(SymInfo* info, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!info->is_init) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "    Initialized: No\n");
        *current_pos += len;
        return;
    }
    
    int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "    Initialized: Yes\n");
    *current_pos += len;
    
    if (info->is_pointer > 0) {
        len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                      "    Init Value: 0x%llx (pointer)\n", (unsigned long long)info->dvalue.ptr_val);
    } else {
        len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                      "    Init Value: %lld\n", (long long)info->dvalue.int_val);
    }
    *current_pos += len;
}

static void format_symbol_details_to_buffer(SymInfo* info, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!info) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "    Info: NULL\n");
        *current_pos += len;
        return;
    }
    
    int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                      "  - Class: %s\n", get_symbol_class_name(info->sym_class));
    *current_pos += len;
    
    len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                  "  - Type: %s\n", get_data_type_name(info->data_type));
    *current_pos += len;
    
    len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                  "  - Address: 0x%llx\n", (unsigned long long)info->addr);
    *current_pos += len;
    
    len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                  "  - Pointer Level: %lld\n", (long long)info->is_pointer);
    *current_pos += len;
    
    format_initialization_info_to_buffer(info, buffer, buffer_size, current_pos);
    
    // 如果是函数，打印参数信息
    if (info->sym_class == SYM_FUNCTION) {
        format_function_params_to_buffer(info->params, buffer, buffer_size, current_pos);
        if (info->func_scope) {
            len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                          "  - Function Scope: Level %d\n", info->func_scope->level);
            *current_pos += len;
        }
    }
    
    // 如果是代码块，打印作用域信息
    if (info->sym_class == SYM_BLOCK) {
        if (info->func_scope) {
            len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                          "  - Block Scope: Level %d\n", info->func_scope->level);
            *current_pos += len;
        }
    }
}

static void format_symbol_info_to_buffer(Symbol* symbol, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!symbol) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "Symbol: NULL\n");
        *current_pos += len;
        return;
    }
    
    int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                      "\nSymbol: %s\n", symbol->name ? symbol->name : "unnamed");
    *current_pos += len;
    
    format_symbol_details_to_buffer(symbol->info, buffer, buffer_size, current_pos);
}

// 格式化单个作用域的所有符号到缓冲区（不递归）
static void format_scope_symbols_only_to_buffer(Scope* scope, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!scope) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "Error: NULL scope\n");
        *current_pos += len;
        return;
    }
    
    // 检查缓冲区空间，如果不够则扩展
    if (*current_pos + 1024 > *buffer_size) {
        *buffer_size *= 2;
        *buffer = (char*)realloc(*buffer, *buffer_size);
        if (!*buffer) {
            return; // 内存分配失败
        }
    }
    
    // 格式化作用域头部信息
    format_scope_header_to_buffer(scope, buffer, buffer_size, current_pos);
    
    // 格式化当前作用域的所有符号（不递归）
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* symbol = scope->hash_table[i];
        while (symbol) {
            // 检查缓冲区空间
            if (*current_pos + 2048 > *buffer_size) {
                *buffer_size *= 2;
                *buffer = (char*)realloc(*buffer, *buffer_size);
                if (!*buffer) {
                    return; // 内存分配失败
                }
            }
            
            format_symbol_info_to_buffer(symbol, buffer, buffer_size, current_pos);
            symbol = symbol->next;
        }
    }
}

// 收集所有作用域的辅助函数
static void collect_all_scopes(Scope* scopes[], int* scope_count) {
    // 收集作用域栈中的所有作用域
    for (int i = 0; i < scope_stack->top; i++) {
        scopes[(*scope_count)++] = scope_stack->stack[i];
    }
    
    // 收集函数作用域和代码块作用域
    for (int level = 0; level < *scope_count; level++) {
        Scope* current_scope = scopes[level];
        
        // 遍历当前层级的符号，查找函数符号和代码块符号的作用域
        for (int i = 0; i < HASH_SIZE; i++) {
            Symbol* symbol = current_scope->hash_table[i];
            while (symbol) {
                if (symbol->info && 
                    (symbol->info->sym_class == SYM_FUNCTION || symbol->info->sym_class == SYM_BLOCK) && 
                    symbol->info->func_scope) {
                    
                    // 检查是否已经在列表中
                    int found = 0;
                    for (int j = 0; j < *scope_count; j++) {
                        if (scopes[j] == symbol->info->func_scope) {
                            found = 1;
                            break;
                        }
                    }
                    
                    // 如果没有找到且有空间，添加到列表
                    if (!found && *scope_count < MAX_SCOPE) {
                        scopes[(*scope_count)++] = symbol->info->func_scope;
                    }
                }
                symbol = symbol->next;
            }
        }
    }
}

// 按层级排序作用域的辅助函数
static void sort_scopes_by_level(Scope* scopes[], int scope_count) {
    for (int i = 0; i < scope_count - 1; i++) {
        for (int j = i + 1; j < scope_count; j++) {
            if (scopes[i]->level > scopes[j]->level) {
                Scope* temp = scopes[i];
                scopes[i] = scopes[j];
                scopes[j] = temp;
            }
        }
    }
}

// 内部函数，按层级格式化到缓冲区
static void format_symbol_table_internal(Scope* scope, char** buffer, size_t* buffer_size, size_t* current_pos) {
    if (!scope) {
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos,
                          "Error: NULL scope in internal traversal\n");
        *current_pos += len;
        return;
    }
    
    // 收集所有作用域并按层级排序
    Scope* scopes[MAX_SCOPE];
    int scope_count = 0;
    
    collect_all_scopes(scopes, &scope_count);
    sort_scopes_by_level(scopes, scope_count);
    
    // 按层级格式化每个作用域
    for (int level = 0; level < scope_count; level++) {
        format_scope_symbols_only_to_buffer(scopes[level], buffer, buffer_size, current_pos);
        
        // 层级之间的分隔
        if (*current_pos + 64 > *buffer_size) {
            *buffer_size += 64;
            *buffer = (char*)realloc(*buffer, *buffer_size);
            if (!*buffer) {
                return;
            }
        }
        int len = snprintf(*buffer + *current_pos, *buffer_size - *current_pos, "\n");
        *current_pos += len;
    }
}

// 获取符号表格式化字符串
char* get_symbol_result_string(Scope* scope) {
    // 如果传入NULL，从全局作用域开始
    if (!scope) {
        if (!scope_stack || scope_stack->top <= 0) {
            char* error_msg = (char*)malloc(64);
            strcpy(error_msg, "Error: No global scope available\n");
            return error_msg;
        }
        scope = scope_stack->stack[0]; // 全局作用域
    }
    
    // 初始化缓冲区
    size_t buffer_size = 4096; // 初始大小4KB
    char* buffer = (char*)malloc(buffer_size);
    if (!buffer) {
        return NULL;
    }
    
    size_t current_pos = 0;
    
    // 添加开始标记
    int len = snprintf(buffer, buffer_size, "=== Symbol Table by Level ===\n");
    current_pos += len;
    
    // 格式化符号表内容
    format_symbol_table_internal(scope, &buffer, &buffer_size, &current_pos);
    
    // 添加结束标记
    if (current_pos + 64 > buffer_size) {
        buffer_size += 64;
        buffer = (char*)realloc(buffer, buffer_size);
        if (!buffer) {
            return NULL;
        }
    }
    
    len = snprintf(buffer + current_pos, buffer_size - current_pos, "=== Level-wise Traversal Complete ===\n");
    current_pos += len;
    
    // 确保字符串以null结尾
    buffer[current_pos] = '\0';
    
    return buffer;
}

// 打印单个作用域的所有符号（不递归）
static void print_scope_symbols_only(Scope* scope) {
    if (!scope) {
        printf("Error: NULL scope\n");
        return;
    }
    
    // 打印作用域头部信息
    print_scope_header(scope);
    
    // 打印当前作用域的所有符号（不递归）
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* symbol = scope->hash_table[i];
        while (symbol) {
            print_symbol_info(symbol);
            symbol = symbol->next;
        }
    }
}

// 按层级打印符号表（不递归进入函数作用域）
void print_symbol_total(Scope* scope) {
    // 如果传入NULL，从全局作用域开始
    if (!scope) {
        if (!scope_stack || scope_stack->top <= 0) {
            printf("Error: No global scope available\n");
            return;
        }
        scope = scope_stack->stack[0]; // 全局作用域
    }
    
    // 打印开始标记
    printf("=== Symbol Table by Level ===\n");
    
    // 收集所有作用域并按层级排序
    Scope* scopes[MAX_SCOPE];
    int scope_count = 0;
    
    collect_all_scopes(scopes, &scope_count);
    sort_scopes_by_level(scopes, scope_count);
    
    // 按层级打印每个作用域
    for (int level = 0; level < scope_count; level++) {
        print_scope_symbols_only(scopes[level]);
        printf("\n"); // 层级之间的分隔
    }
    
    // 打印结束标记
    printf("=== Level-wise Traversal Complete ===\n");
}

// 统一的哈希函数 - 计算字符串哈希值
unsigned int hash_string(const char* str) {
    unsigned int hash = 0;
    while (*str) {
        hash = hash * 31 + *str++;
    }
    return hash % HASH_SIZE;
}

// 类型转换辅助函数
DataType convert_type(int old_type) {
    int base_type;
    if (old_type == CHAR)
        return TYPE_CHAR;
    else if (old_type == INT)
        return TYPE_INT;
    else if (old_type >= PTR) {
        // 检查基础类型：去掉所有PTR后剩下的类型
        base_type = old_type;
        while (base_type >= PTR) {
            base_type -= PTR;
        }
    }
    if (base_type == CHAR)
        return TYPE_PTR_CHAR;
    else
        return TYPE_PTR_INT;
    return TYPE_INT; // 默认
}

// 获取指针级别
int get_pointer_level(int old_type) {
    if (old_type < PTR)
        return 0;
    return (old_type - PTR) / PTR + 1; // PTR的倍数表示指针级别
}

// 类转换辅助函数
SymClass convert_class(int old_class) {
    if (old_class == Glo)
        return SYM_GLOBAL;
    else if (old_class == Loc)
        return SYM_LOCAL;
    else if (old_class == Para)
        return SYM_PARAM;
    else if (old_class == Fun)
        return SYM_FUNCTION;
    else if (old_class == Sys)
        return SYM_SYSTEM;
    else if (old_class == Enum)
        return SYM_ENUM;
    else if (old_class == Block)
        return SYM_BLOCK;
    
    return SYM_GLOBAL; // 默认
}

// 创建符号信息
SymInfo* create_symbol_info(const char* name, int old_type, int old_class, intptr_t addr) {
    SymInfo* info = (SymInfo*)malloc(sizeof(SymInfo));
    memset(info, 0, sizeof(SymInfo));
    
    info->name = strdup(name);
    info->data_type = convert_type(old_type);
    info->sym_class = convert_class(old_class);
    info->addr = addr;
    info->is_pointer = get_pointer_level(old_type);
    info->scope = current_scope(scope_stack);
    
    return info;
}

// 创建作用域
Scope* create_scope(Scope* parent) {
    Scope* scope = (Scope*)malloc(sizeof(Scope));
    memset(scope, 0, sizeof(Scope));
    
    scope->parent = parent;
    scope->level = parent ? parent->level + 1 : 0;
    
    return scope;
}

// 添加符号到作用域
Symbol* add_symbol(Scope* scope, const char* name, SymInfo* info) {
    // 使用统一的哈希函数
    unsigned int hash = hash_string(name);

    // 创建符号
    Symbol* sym = (Symbol*)malloc(sizeof(Symbol)); // 创建一个哈希表的value，value是一个pair
    sym->name = strdup(name); // 复制字符串而不是直接使用指针
    sym->info = info;
    
    // 添加到哈希表
    sym->next = scope->hash_table[hash]; // 用头插法，将新符号添加到哈希表的头部
    scope->hash_table[hash] = sym;
    
    return sym;
}

// 在当前作用域查找符号
Symbol* find_symbol_current(Scope* scope, const char* name) {
    if (!scope) return NULL;
    
    // 使用统一的哈希函数
    unsigned int hash = hash_string(name);
    
    // 在哈希链表中查找
    Symbol* sym = scope->hash_table[hash];
    while (sym) {
        if (strcmp(sym->name, name) == 0) {
            return sym;
        }
        sym = sym->next;
    }
    
    return NULL;
}

// 在所有作用域中查找符号
Symbol* find_symbol_all(ScopeStack* stack, const char* name) {
    Scope* scope = current_scope(stack);
    
    while (scope) {
        Symbol* sym = find_symbol_current(scope, name);
        if (sym) {
            return sym;
        }
        scope = scope->parent;
    }
    
    return NULL;
}

// 获取当前作用域，top指向的栈顶为空闲位置
Scope* current_scope(ScopeStack* stack) {
    if (stack->top <= 0) return NULL;
    return stack->stack[stack->top - 1];
}

// 压入新作用域
void push_scope(ScopeStack* stack) {
    if (stack->top >= MAX_SCOPE) {
        printf("Error: Maximum scope nesting level exceeded\n");
        exit(-1);
    }
    
    Scope* parent = current_scope(stack);
    Scope* new_scope = create_scope(parent);
    stack->stack[stack->top++] = new_scope; // 栈顶为空闲位置
}

// 弹出作用域
void pop_scope(ScopeStack* stack) {
    if (stack->top <= 1) {
        printf("Error: Cannot pop global scope\n");
        return;
    }
    
    stack->top--;
}

// 释放作用域内存
void free_scope(Scope* scope) {
    if (!scope) return;
    
    // 释放所有符号
    for (int i = 0; i < HASH_SIZE; i++) {
        Symbol* sym = scope->hash_table[i];
        while (sym) {
            Symbol* next = sym->next;
            free((void*)sym->info->name);
            free(sym->info);
            free(sym);
            sym = next;
        }
    }
    
    free(scope);
}

// 释放作用域栈
void free_scope_stack(ScopeStack* stack) {
    for (int i = 0; i < stack->top; i++) {
        free_scope(stack->stack[i]);
    }
    free(stack);
}

/**
 * 全局初始化函数 - 初始化编译器环境
 * 
 * @param pool_size 内存池大小
 * @param code 要分析的源代码
 */
void init_compiler_memory(int pool_size, const char* code) {
    // 分配内存
    pool_size = pool_size * 2;
    poolsize = pool_size;
    
    // 分配各内存段
    if (!(text = text_start = malloc(poolsize))) {
        printf("无法为代码段分配内存\n");
        return;
    }
    if (!(data = data_start = malloc(poolsize))) {
        printf("无法为数据段分配内存\n");
        free(text);
        return;
    }
    if (!(stack = stack_start = malloc(poolsize))) {
        printf("无法为栈分配内存\n");
        free(text);
        free(data);
        return;
    }
    if (!(symbols = symbols_start = malloc(poolsize))) {
        printf("无法为符号表分配内存\n");
        free(text);
        free(data);
        free(stack);
        return;
    }
    
    // 初始化内存区域
    memset(text, 0, poolsize);
    memset(data, 0, poolsize);
    memset(stack, 0, poolsize);
    memset(symbols, 0, poolsize);

    
    // 初始化寄存器
    bp = sp = (intptr_t *)((intptr_t)stack + poolsize);
    ax = 0;
    
    // 初始化词法分析器
    // 释放之前的内存
    if (old_src) {
        free(old_src);
        old_src = NULL;
    }
    
    if (code) {
        src = old_src = strdup(code);
    } else {
        src = old_src = strdup("");
    }
    
    
}
